package is.progetto1.aritmeticExpression;

import is.progetto1.exception.IllegalContextException;

public class AddOp extends Operator {

	private int mode;
	
	public AddOp(int mode){
		if (mode!=ADD_MODE && mode!=SUB_MODE) {
			throw new IllegalArgumentException("Illegal mode:" + mode);
		}
		this.mode=mode;
	}

	public AddOp(Expression parent, int mode){
		this(mode);
		this.parent=parent;
	}

	public AddOp(Expression left, Expression right, Expression parent,
			int mode) {
		this(parent,mode);
		this.left = left;
		this.right = right;
	}
	
	public int getMode() {
		return mode;
	}

	public void setMode(int mode) {
		if (mode!=ADD_MODE || mode!=SUB_MODE) {
			throw new IllegalArgumentException("Illegal mode:" + mode);
		}
		this.mode=mode;
	}

	@Override
	public final int toAssess(Context c) throws IllegalContextException {
		int res1 = 0, res2 = 0;
		if (left != null) {
			res1 = left.toAssess(c);
		}
		if (right != null) {
			res2 = right.toAssess(c);
		}
		if (mode==ADD_MODE) {
			return res1 + res2;
		} else {
			return res1 - res2;
		}
	}

	@Override
	public final String toString() {
		if (right != null && left != null){
			if(mode==ADD_MODE){
			return "(" + left.toString() + " + " + right.toString()
					+ ")";
			}else{
				return "(" + left.toString() + " - " + right.toString()
						+ ")";
			}
		}
		return "()";
	}

	@Override
	public final int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((left == null) ? 0 : left.hashCode());
		result = prime * result + ((right == null) ? 0 : right.hashCode());
		return result;
	}

	@Override
	public final boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		AddOp other = (AddOp) obj;
		if (left == null) {
			if (other.left != null)
				return false;
		} else if (!left.equals(other.left))
			return false;
		if(mode != other.mode){
			return false;
		}
		if (right == null) {
			if (other.right != null)
				return false;
		} else if (!right.equals(other.right))
			return false;
		return true;
	}

	@Override
	public String getOperator() {
		if(mode==ADD_MODE)
			return "+";
		return "-";
	}
}
